package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

public class Languageapp_Discover_Videolist_Adapter  extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;

	private Activity activity;
	private Context context;
	
	private String NID;
	
	static String json = ""; 
	
	static InputStream is = null;
	HttpParams httpParameters = new BasicHttpParams();
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;
	
	private static byte[] buff =new byte[1024];

	
	private String[] NID_s;
	private String[] MID_s;
	private String[] M_Source_s;
	
	public Languageapp_Discover_Videolist_Adapter(Activity activity,String NID) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.NID = NID;

	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Loading Video List", "Loading",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		
		try {
			
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);			
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			
			/*HttpPost httppost = new HttpPost(RegisterUserLink);*/
			HttpPost httppost = new HttpPost(urls[0]);
			JSONObject json = new JSONObject();
			
			json.put("record1", NID);

			JSONArray postjson = new JSONArray();
			postjson.put(json);
			httppost.setHeader("json", json.toString());
			httppost.getParams().setParameter("jsonpost", postjson);
			httppost.setEntity(new UrlEncodedFormEntity(
					nameValuePairs));
			HttpResponse httpResponse = httpclient.execute(httppost);
			
			HttpEntity httpEntity = httpResponse.getEntity();
			
			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
			
			/*try{
				jobj = new JSONObject(json);
				
			}catch(JSONException e){
				Log.e("User register Service","Error parsing data"+e.toString());
			}*/
			
			//return jobj;
			
		return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		
		Log.d("Post Exec", result);
		
		try {
			
			JSONObject respObj = new JSONObject(result);
			
			//JSONObject value = respObj.getJSONObject("posts");
			
			JSONArray appLink = respObj.getJSONArray("posts");
			//JSONArray appLink = new JSONArray(result);
			
			Log.e("Size", ""+appLink.length());
			
			NID_s = new String[appLink.length()];
			MID_s = new String[appLink.length()];
			M_Source_s = new String[appLink.length()];
			
				for(int i=0;i<appLink.length();i++){
					JSONObject match = appLink.getJSONObject(i);
					
					Log.e("NID", match.getString("NID"));
					
					NID_s[i] = match.getString("NID");
					MID_s[i] = match.getString("MID");
					M_Source_s[i] = match.getString("M_Source");
					
				}

				ListView lstView=(ListView)activity.findViewById(R.id.listViewVideoSynonyms);
				lstView.setAdapter(new ImgViewBaseAdap(activity.getApplicationContext()));
				

		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

	class ImgViewBaseAdap extends BaseAdapter{
		
		 private Context context;
		 LayoutInflater inflater;
		 
		 private boolean bVideoIsBeingTouched = false;
		 private boolean firstTouch = false;
		 private Handler mHandler = new Handler();
		 

		public ImgViewBaseAdap(Context context) {
			this.context = context;
			this.inflater = LayoutInflater.from(context);
			
		}
		
		@Override
		public View getView(int position,View convertView,ViewGroup parent){
			
			final ViewHolder holder;
			final int pospass = position;
			
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.languageapp_discover_video, null);
                holder = new ViewHolder();
                
                holder.textView = (TextView)convertView.findViewById(R.id.addnew);
                holder.videoVw = (VideoView)convertView.findViewById(R.id.videoview_example);
                holder.imgView = (ImageView)convertView.findViewById(R.id.ImageView_example);
               
                final MediaController mediaController = new MediaController(activity);
                
                mediaController.show();
                
                mediaController.setAnchorView(holder.videoVw);
                holder.videoVw.setMediaController(mediaController);
                 
                holder.videoVw.setVideoURI(Uri.parse(M_Source_s[position]));
                
                /////////////////////////////
                
                /*Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(M_Source_s[position],
                		MediaStore.Video.Thumbnails.MICRO_KIND);*/
                
                //holder.imgView.setImageBitmap(thumbnail);

                //BitmapDrawable bitmapDrawable = new BitmapDrawable(thumbnail);
                
                //holder.videoVw.setBackgroundDrawable(bitmapDrawable);
                
            /*    ThumbnailAsync asy = new ThumbnailAsync(holder.imgView);
                asy.execute(M_Source_s[position]);*/
                
                /////////////////////////////
                
                Log.e("M_Source_s[position]", M_Source_s[position]);
                
                holder.videoVw.requestFocus();
                
                holder.videoVw.setOnPreparedListener(new OnPreparedListener() {
                 public void onPrepared(MediaPlayer mp) {
                	 progdialod.dismiss();
                	 //holder.videoVw.start();
                	 
                 }
                });
                
                holder.videoVw.setOnTouchListener(new View.OnTouchListener() {
 					@Override
 					public boolean onTouch(View v, MotionEvent event) {
 						mediaController.show();
 						
 							holder.videoVw.setOnPreparedListener(new OnPreparedListener() {
 			                 public void onPrepared(MediaPlayer mp) {
 			                	 //progdialod.dismiss();
 			                	 holder.videoVw.start();
 			                 }
 			                });

 		                    return true;
 					}
                 });
                
                
                
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
			
			
			holder.textView.setText(NID_s[position]);

            return convertView;
		}

		@Override
		public int getCount() {
			return NID_s.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		
	}

	public static class ViewHolder {
        public TextView textView;
        public VideoView videoVw;
        public ImageView imgView;
        
    }

	
}
